$(function () {
    /**
     * 初始化添加或修改页面
     */ 
	(function initSelectBoxs(){
		// 判断是执行添加还是执行更新，role_id不为空时执行修改，否则执行添加
		$('#codesave').val(code);
		$('#add_role_form input[name="name"]').val(name);
		$('.role_desc').val(roledesc);
		fms.InitSingleSelectByStatic({id:"role_status",data:fms.constants.SELECT.SELECT_STATUS});// 根据状态初始化下拉选项
		$.ajax({// 根据用户主键id查询用户信息
		    type: "post",
		    dataType: "json",
		    data: {'id': role_id},
		    cache:false,
		    async: false,// 同步
		    url: ctxPath + "/menu/getTreeList.do",
		    success: function (data) {
		    	$.each(data, function (i, v) {
					var html = "";
					var flag =  v['checked']==true ? 'checked="true"':'';
					var ddId = "dd_"+v['id'];
					var pid = "pid_"+v['id'];
					var text=v['text'];
					var attributes=v['attributes'];
					if (v['pid'] == '0') {
						
						html += "<div class='row'>"
							 + "<label style='font-weight: bold;'>"
							 + "<input type='checkbox' value=" + attributes + " id="+pid+" "+flag+"/>"
							 + "" + text + "</label>"
							 + "<div class='panel-body row' style='padding-left: 25px;' id="+ddId+">"
							 + "</div>"
							 + "</div>"
		        	}
					$("#main").append(html);
					$("#"+pid).change(function() {
						if($("#"+pid).is(':checked')) {
							$('.'+v['id']).prop("checked", true);
						}
						else
						{
							$('.'+v['id']).prop("checked", false);
						}
					});
				});
				$.each(data, function (i, v) {
					var text=v['text'];
					var attributes=v['attributes'];
					if (v['pid'] != '0')
					{	
						var flag =  v['checked']==true ? 'checked="true"':'';
						
						var childMenu ="<div class='col-xs-3'>"
										+ "<label>"
										+ "<input type='checkbox' value=" + attributes + " class="+v['pid']+" "+flag+">"
										+ "" + text + "</label>"
										+ "</div>"
			
						$("#dd_"+v['pid']).append(childMenu);
					}
				});
		    },
		    error: function (data) {
		        fms.ShowMsg({msg:"取菜单数据错误！", icon:2, data:data});
		    }
		});
	})();
	
    /**
     * 点击保存
     */ 
    $("#role_go_add").on("click", function (e, treeId, treeNode) {
        var nodes=[];
        var domList = $("#main input[type='checkbox']");
        $.each(domList, function (i, v) {
        	if(v.checked ==true){
        		nodes.push({attributes:v.value});
        	}
        });
        var id;
        var roleurl;
        var code = $('#codesave').val();
        var name = $('#add_role_form input[name="name"]').val();
        var role_desc = $('.role_desc').val();
        var status = $("#role_status").val();
        if ($('#add_role_form').valid()) {
            if (role_id.length < 1) {// 为什么这么判断，有点问题。
                id = window.fms.guid();// 获取js生成的32位UUID，作为用户表的主键，因为中间表要保存用户的id。
               	saveAndUpdate({id:id,code:code,name:name,nodes:nodes,role_desc:role_desc,status:status,url:ctxPath + "/role/saveRole.do "});
            } else {
                id = role_id;
                saveAndUpdate({id:id,code:code,name:name,nodes:nodes,role_desc:role_desc,status:status,url:ctxPath + "/role/toupdateRole.do"});
            }
        }
    });
    
	/**
	 * 保存或修改
	 */
    function saveAndUpdate(param){
    	var roleAndMenuList = [];
        $.each(param.nodes, function (i, node) {
            var temp = window.fms.guid();// 获取js生成的32位UUID，作为用户表的主键，因为中间表要保存用户的id。
            // 封装传入前台的roleAndMenuList
            roleAndMenuList.push({id: temp,roleId: param.id,menuId: node.attributes});
        });
        var role = {id: param.id,code: param.code,name: param.name,roleDesc: param.role_desc,status: param.status,orgDate:new Date(),roleAndMenuList: roleAndMenuList};
        roleurl = param.url;
        $.ajax({
            type: "POST",
            dataType: "json",
            contentType: "application/json",
            traditional: true,
            url: roleurl,
            async: false,// 同步：意思是当有返回值以后才会进行后面的js程序。
            data: JSON.stringify(role),// 将role对象转换成json字符串。
            success: function (data) {
                layer.msg("保存成功！", {
                    icon: 1,
                    time: 1000
                }, function (index) {
                    layer.close(index);
                    window.location.href = ctxPath + "/role/index.do";
                });
            }
        });
    }
    
    /**
     * 表单校验规则
     */ 
    $("#add_role_form").validate({
        rules: {
            code: {
                required: true,
                minlength: 1,
                remote: fms.RemoteValidate({url:ctxPath + "/role/validateRole.do",data:{"id":role_id,"code":function(){return $('#codesave').val();}}})
            },
            name: {
                required: true,
                minlength: 2,
                remote: fms.RemoteValidate({url:ctxPath + "/role/validateRole.do",data:{"id":role_id,"name":function(){return $('#add_role_form input[name="name"]').val();}}})
            }
        },
        messages: {
            code: {
                required: "请输入角色编号",
                minlength: "至少一个个字符！",
                remote: "角色编号重复"
            },
            name: {
                required: "请输入角色名称",
                minlength: "至少两个字符！",
                remote: "角色名称重复"
            }
        },
        errorLabelContainer: $("#add_role_form div.error")
    });
});
